package com.sg.business.permission.adapter.doc;

import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.runtime.Platform;

import com.mobnut.db.DBActivator;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.sg.business.model.IModelConstants;
import com.sg.business.model.ProjectRole;
import com.sg.business.model.ProjectRoleAssignment;
import com.sg.business.permission.model.IACLControlable;
import com.sg.business.permission.model.IPermissionScope;
import com.sg.widgets.part.CurrentAccountContext;

public class PermissionSettingTest extends PropertyTester {

	public PermissionSettingTest() {
	}

	@Override
	public boolean test(Object receiver, String property, Object[] args,
			Object expectedValue) {
		IACLControlable aclControlable;
		if (receiver instanceof IACLControlable) {
			aclControlable = (IACLControlable) receiver;
		} else {
			aclControlable = (IACLControlable) Platform.getAdapterManager()
					.getAdapter(receiver, IACLControlable.class);
		}
		if (aclControlable == null) {
			return false;
		}

		CurrentAccountContext context = new CurrentAccountContext();
		if (context.getAccountInfo() == null) {
			return false;
		}
		String userId = context.getConsignerId();
		IPermissionScope projectScope = aclControlable.getProjectScope();
		if (projectScope == null) {
			return false;
		}
		Object projectId = projectScope.getId();
		DBCollection col = DBActivator.getCollection(IModelConstants.DB,
				IModelConstants.C_PROJECT_ROLE_ASSIGNMENT);
		long cnt = col.count(new BasicDBObject()
				.append(ProjectRoleAssignment.F_USER_ID, userId)
				.append(ProjectRoleAssignment.F_ROLE_NUMBER,
						ProjectRole.ROLE_PROJECT_DOCUMENT_ADMIN_ID)
				.append(ProjectRoleAssignment.F_PROJECT_ID, projectId));
		return cnt > 0;
	}

}
